#include <ds18b20.h>

DS18b20::DS18b20(int pin)
{
    this->pin = pin;
}

void DS18b20::init()
{
    ow = mgos_onewire_create(pin);
    if (ow == NULL)
    {
        printf("one wire init failed.\n");
    }
    else
    {
        printf("one wire init successful.\n");
        printf("pin is :%d\n", ow->pin);
    }
}

double DS18b20::getTemp()
{
    return temp;
}

void DS18b20::begin_conversion()
{
    if (ow == NULL)
    {
        printf("one wire is NULL.\n");
        return;
    }

    if (mgos_onewire_reset(ow))
    {
        mgos_onewire_skip(ow);
        mgos_onewire_write(ow, 0x44);
        //wait
        mgos_set_timer(750, false, cb_read, this);
    }
    else
    {
        printf("failed to reset ds18b20!\n");
    }
}

// 转换到浮点
double DS18b20::toDouble(uint16_t data)
{
    if (data & 0x8000)
        return -1 * ((uint16_t)(~data + 1) / 256.0f);
    else
        return (data / 256.0f);
}